// pages/goods/price-chart/price-chart.js
//调用方式/pages/goods/price-chart/price-chart?goodDetail=xxxx


import * as echarts from '../../../ec-canvas/echarts';
var httpUtil = require('../../../utils/httpUtil.js')
var uiUtil = require('../../../utils/uiUtil.js')
var util = require('../../../utils/util.js')
var emptyUtil = require('../../templates/empty/empty.js')
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodDetail: null, //订单信息

    priceWeekList: [], //价格走势
    priceWeekEchartsInit: false,
    priceMonthList: [],
    priceMonthEchartsInit: false,
    priceYearList: [],
    priceYearEchartsInit: false,

    emptyParam: {
      emptyStatus: 0
    },

    curTopBarIndex: 0,

    yAxisColorList: ['#D6D6D6'], //分割线颜色
    seriesColorList: ['#2392FF', '#56B2BA', '#E92C81', '#E92C81'], //折现颜色
    areaColorOffset0List: ['#2392FF', '#56B2BA', '#E92C81', '#FACE15'], //区域颜色
    areaColorOffset05List: ['#2392FF', '#56B2BA', '#E92C81', '#FACE15'],
    areaColorOffset1List: ['#FFF'],
    priceEc1: {
      lazyLoad: true // 将 lazyLoad 设为 true 后，需要手动初始化图表
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this
    var goodDetail = JSON.parse(decodeURIComponent(options.goodDetail))
    this.setData({
      goodDetail: goodDetail
    })
    uiUtil.showLoading("正在加载..")
    this.requestGoodPriceChart()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.priceChatDom = this.selectComponent('#weekDom0');
  },
  onShareAppMessage: function (res) {
    return util.handleShareApp()
  },
  /**
   * 获取正在进行中的订单数据
   */
  requestGoodPriceChart() {
    var goodDetail = this.data.goodDetail
    httpUtil.PostRequest("good_price_list", {
      goodId: goodDetail.goodId,
      skuId: goodDetail.skuId,
    }, {
      success(res) {
        var priceWeekList = res.priceWeekList || []
        var priceMonthList = res.priceMonthList || []
        var priceYearList = res.priceYearList || []

        var priceWeekListLength = priceWeekList.length
        var priceMonthListLength = priceMonthList.length
        var priceYearListLength = priceYearList.length

        if (priceWeekListLength == 0 && priceMonthListLength == 0 && priceYearListLength.length == 0) { //无数据
          emptyUtil.showEmptyView()
        } else {
          var defSelectIndex = 0 //默认选中的选项卡index
          //遍历设置ec名字
          if (priceWeekListLength != 0) {
            for (var i = 0; i < priceWeekListLength; i++) {
              priceWeekList[i].tEcName = "weekEc" + i
              priceWeekList[i].tIdName = "weekId" + i
              priceWeekList[i].tDomName = "weekDom" + i
            }
            if (defSelectIndex == 0) {
              defSelectIndex = 1
            }
          }
          if (priceMonthListLength != 0) {
            for (var i = 0; i < priceMonthListLength; i++) {
              priceMonthList[i].tEcName = "monthEc" + i
              priceMonthList[i].tIdName = "monthId" + i
              priceMonthList[i].tDomName = "monthDom" + i
            }
            if (defSelectIndex == 0) {
              defSelectIndex = 2
            }
          }
          if (priceYearListLength != 0) {
            for (var i = 0; i < priceYearListLength; i++) {
              priceYearList[i].tEcName = "yearEc" + i
              priceYearList[i].tIdName = "monthId" + i
              priceYearList[i].tDomName = "yearDom" + i
            }
            if (defSelectIndex == 0) {
              defSelectIndex = 3
            }
          }


          that.setData({
            priceWeekList: priceWeekList,
            priceMonthList: priceMonthList,
            priceYearList: priceYearList
          })
          if (defSelectIndex == 1) {
            that.onSwithTabBar1()
          } else if (defSelectIndex == 2) {
            that.onSwithTabBar2()
          } else if (defSelectIndex == 3) {
            that.onSwithTabBar3()
          }

        }
      },
      fail(code, res) {
        var text = res || "获取价格走势失败"
        emptyUtil.showFailView(text)
      },
      complete() {
        uiUtil.hideLoading()
      }
    })
  },

  onSwithTabBar1() {
    if (this.data.curTopBarIndex == 1) {
      return
    } else {
      this.setData({
        curTopBarIndex: 1
      })

      if (!this.data.priceWeekEchartsInit) {
        //初始化echart数据
        that.initPriceChart(this.data.priceWeekList)
        this.setData({
          priceWeekEchartsInit: true
        })
      }

    }
  },
  onSwithTabBar2() {
    if (this.data.curTopBarIndex == 2) {
      return
    } else {
      this.setData({
        curTopBarIndex: 2
      })
      if (!this.data.priceMonthEchartsInit) {
        //初始化echart数据
        that.initPriceChart(this.data.priceMonthList)
        this.setData({
          priceMonthEchartsInit: true
        })
      }

    }
  },
  onSwithTabBar3() {
    if (this.data.curTopBarIndex == 3) {
      return
    } else {
      this.setData({
        curTopBarIndex: 3
      })
      if (!this.data.priceYearEchartsInit) {
        //初始化echart数据
        that.initPriceChart(this.data.priceYearList)
        this.setData({
          priceYearEchartsInit: true
        })
      }

    }
  },


  /**
   * 初始化图标
   */
  initPriceChart(list) {
    for (var i = 0; i < list.length; i++) {

      var item = list[i]
      var priceList = item.priceList
      var colorList = []
      var yAxisColor = this.data.yAxisColorList[i % (this.data.yAxisColorList.length)]
      var seriesColor = this.data.seriesColorList[i % (this.data.seriesColorList.length)]
      var areaColorOffset0 = this.data.areaColorOffset0List[i % (this.data.areaColorOffset0List.length)]
      var areaColorOffset05 = this.data.areaColorOffset05List[i % (this.data.areaColorOffset05List.length)]
      var areaColorOffset1 = this.data.areaColorOffset1List[i % (this.data.areaColorOffset1List.length)]
      colorList.push(yAxisColor)
      colorList.push(seriesColor)
      colorList.push(areaColorOffset0)
      colorList.push(areaColorOffset05)
      colorList.push(areaColorOffset1)

      this.setChartInit(item, colorList)
    }
  },

  setChartInit: function(priceItem, colorList) {
    var dom = this.selectComponent('#' + priceItem.tDomName);
    var priceList = priceItem.priceList;
    dom.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });

      //整理横坐标，value值
      var xDatas = []
      var yValues = []

      var priceListLength = priceList.length
      for (var j = 0; j < priceListLength; j++) {
        var item = priceList[j]
        xDatas.push(item.date)
        yValues.push(item.price)
      }
      that.setChartOption(chart, xDatas, yValues, colorList);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },


  setChartOption: function(chart, xDatas, yValues, colorList) {
    var option = {
      grid: {
        top: '10%',
        bottom: '18%',
        left: '15%'
      },
      tooltip: {
        show: true,
        trigger: 'axis',
       
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xDatas,
        axisLabel: {
          color: '#969696'
        },
      },
      yAxis: {
        x: 'center',
        type: 'value',
        axisLabel: {
          color: '#C6C6C6'
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: [colorList[0]]
          }
        },
        //   show: false
      },
      series: [{
        type: 'line',
        data: yValues,
        showSymbol: true,
        symbol: 'circle', //设定为实心点
        color: [colorList[1]], //折现颜色
        areaStyle: {
          normal: {
            opacity: 0.3,
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1, [{
                  offset: 0,
                  color: colorList[2]
                },
                {
                  offset: 0.3,
                  color: colorList[3]
                },
                {
                  offset: 1,
                  color: colorList[4]
                }
              ]
            )
          }
        },
      }]
    };

    chart.setOption(option);
  }


})